﻿#include "downloadmanager.h"

#include<QDir>
#include<QDir>
#include<QJsonDocument>
#include<QJsonArray>
#include<QDebug>
int DownLoadManager::id;


DownLoadManager::DownLoadManager()
{

}

DownLoadManager::DownLoadManager(QString name)
{
    file.setFileName(QDir::currentPath()+"/userfolder/"+name+"/download.json");
    if(!file.open(QIODevice::ReadWrite))
        qDebug()<<"open file failed";
    QJsonDocument jsonDoc=QJsonDocument::fromJson(file.read(file.size()));
    QJsonObject jsonObject=jsonDoc.object();
    id=jsonObject.value("id").toInt();
    path=jsonObject.value("path").toString();
    if(path==""){
        path="C:/qtbrowser/download";
    }
    QJsonArray items=jsonObject.value("download").toArray();
    for(auto item : items)
    {
        QJsonObject dataObject=item.toObject();

        DownLoadItem downLoadItem(
                    dataObject.value("path").toString(),
                    dataObject.value("time").toString(),
                    dataObject.value("name").toString(),
                    dataObject.value("id").toInt());
        list.append(QVariant::fromValue(downLoadItem));
    }

}
DownLoadManager::~DownLoadManager()
{
    file.remove();
    QJsonObject jsonObject;
    QJsonArray arr;
    for(auto x : list)
    {
        QJsonObject dataObject;
        DownLoadItem item=x.value<DownLoadItem>();
        dataObject.insert("path", item.path());
        dataObject.insert("time", item.time());
        dataObject.insert("name",item.name());
        dataObject.insert("id",item.id());

        arr.push_back(dataObject);
    }
    jsonObject.insert("download",arr);
    jsonObject.insert("id",id);
    jsonObject.insert("path",path);
    QJsonDocument jsonDoc(jsonObject);

    if(!file.open(QIODevice::WriteOnly))
        qDebug()<<"open file failed";
    file.seek(0);
    file.write(jsonDoc.toJson());
    file.close();
}

QString DownLoadManager::getPath()
{
    return path;
}

void DownLoadManager::setPath(QString t_path)
{
    t_path = t_path.remove(0,8);
    path=t_path;
    qDebug()<<"C++"<<path;
    emit pathChanged();
}
void DownLoadManager::add(QString path,QString name,QString time){
    qDebug()<<"add";
    DownLoadItem item(path,time,name,id++);
    list.append(QVariant::fromValue(item));
    emit listChanged();
}

void DownLoadManager::remove(int id){
    for(auto &x:list)
    {
        DownLoadItem item=x.value<DownLoadItem>();
        if(item.id()==id)
        {
            list.removeOne(x);
            return;
        }
    }
    emit listChanged();
}
void DownLoadManager::removeAll(){
    list.clear();
    emit listChanged();
}

bool DownLoadManager::open(QString path)
{
    bool bRet = QDesktopServices::openUrl(QUrl(path));
    if(!bRet)
    {
        qDebug()<<"open folder failed";
        return false;
    }else{
        return true;
    }
}
QVariantList DownLoadManager:: getDownLoadItemList(){
    return list;
}
